//
//  SEExamineRecordViewController.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/9.
//

import UIKit
import DNSPageView

private let kDefaultHeaderHeight: CGFloat = 140

class SEExamineRecordViewController: SEBaseViewController {

    var viewModel = SEExamineRecordViewModel()

    init(with model: SEPatientFileHealthModel) {
        self.viewModel.heathModel = model
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        requestExamineRecordDetail()
    }

    override func setupUI() {
        super.setupUI()

        guard viewModel.recordModels.count > 0 else {
            setViewModelUpdateDataHandler()
            return
        }
        
        view.addSubview(contentView)
        contentView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().priority(.low)
            make.top.equalToSuperview().offset(UIScreen.navigationBarMaxY)
        }

        headerView.updateWithViewModel(viewModel.heathModel)
        contentView.tableHeaderView = headerView
        headerView.snp.makeConstraints { (make) in
            make.left.top.equalTo(0)
            make.size.equalTo(CGSize(width: UIScreen.screenWidth, height: kDefaultHeaderHeight))
        }
        
        view.addSubview(advisoryButton)
        advisoryButton.snp.makeConstraints { (make) in
            make.left.equalTo(15)
            make.right.equalToSuperview().offset(-15)
            make.bottom.equalToSuperview().offset(-30)
            make.height.equalTo(50)
        }
        advisoryButton.layer.cornerRadius = 50 / 2
    }

    private func setViewModelUpdateDataHandler() {
        viewModel.updateData = { [weak self] (status) in
            switch status {
            case .success:
                self?.setupUI()
            case .auth(let msg):
                self?.presentLoginViewController(selector: #selector(self?.requestExamineRecordDetail), handle: {
                    SEHUD.showError(message: msg)
                })
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }

    // MARK: - getter
    
    private lazy var contentView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.backgroundColor = .background
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        tableView.isScrollEnabled = false
        tableView.showsVerticalScrollIndicator = false
        tableView.dataSource = self
        tableView.delegate = self
        
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: UITableViewCell.reuseIdentifier())
        
        return tableView
    }()
    
    private lazy var pageViewManager: PageViewManager = {
        let style = PageStyle()
        style.isShowBottomLine = true
        style.isTitleScaleEnabled = true
        style.isTitleViewScrollEnabled = true
        style.titleFont = UIFont.regular(14)
        style.titleColor = Asset.textDark.color
        style.titleSelectedColor = Asset.main.color
        style.bottomLineColor = Asset.main.color
        style.bottomLineWidth = 30
        style.bottomLineRadius = 2

        var titles: [String] = []

        for item in viewModel.recordModels {
            if item.checkItemCode == 101 || item.checkItemCode == 102  {
                let controller = SEExamineRecordFundusController()
                controller.viewModel = SEExamineRecordFundusViewModel(model: item)
                titles.append(item.checkItemValue)
                addChild(controller)
            }
            if item.checkItemCode == 103 {
                let controller = SEExamineRecordEyePressureController()
                controller.viewModel = SEExamineRecordEyePressureViewModel(model: item)
                titles.append(item.checkItemValue)
                addChild(controller)
            }
            if item.checkItemCode == 104 {
                let controller = SEExamineRecordVisionController()
                controller.viewModel = SEExamineRecordVisionViewModel(model: item)
                titles.append(item.checkItemValue)
                addChild(controller)
            }
            if item.checkItemCode == 105 {
                let controller = SEExamineRecordRefractiveController()
                controller.viewModel = SEExamineRecordRefractiveViewModel(model: item)
                titles.append(item.checkItemValue)
                addChild(controller)
            }
            if item.checkItemCode == 106 || item.checkItemCode == 107 {
                let controller = SEExamineRecordOctViewController()
                controller.viewModel = SEExamineRecordOctViewModel(model: item)
                titles.append(item.checkItemValue)
                addChild(controller)
            }
        }
        
        return PageViewManager(style: style, titles: titles, childViewControllers: children)
    }()
    
    private lazy var headerView = UINib.loadViewFrom(SEExamineRecordHeaderView.self)
    
    private lazy var advisoryButton: UIButton = {
        let button = UIButton(frame: .zero)
        button.backgroundColor = Asset.main.color
        button.setTitle("专家图文咨询", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.setTitleColor(UIColor.white.withAlphaComponent(0.8), for: .highlighted)
        button.addTarget(self, action: #selector(advisoryAction), for: .touchUpInside)
        return button
    }()
}

extension SEExamineRecordViewController {
    @objc private func advisoryAction() {
        pushToDoctorList()
    }

    private func pushToDoctorList() {
//        let patientDetailModel = SEPatientDetailModel(id: viewModel.examineDetailViemModel.model.patId, name: viewModel.examineDetailViemModel.model.name)
//        let patientDetailVm = SEPatientDetailViewModel(model: patientDetailModel)
//        let vc = SEDoctorListViewController(fromType: .hospitalize, examineRecordVm: viewModel, patientInfo: patientDetailVm)
//        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - UITableViewDataSource

extension SEExamineRecordViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.reuseIdentifier(), for: indexPath)
        cell.contentView.backgroundColor = .background
        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.contentView.addSubview(pageViewManager.contentView)
        pageViewManager.contentView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(1)
            make.left.right.bottom.equalToSuperview()
        }
    }
}

extension SEExamineRecordViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return pageViewManager.titleView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UIScreen.screenHeight - UIScreen.navigationBarMaxY - kDefaultHeaderHeight
    }
}

// MARK: - APIRequest

extension SEExamineRecordViewController {
    @objc func requestExamineRecordDetail() {
        viewModel.requestExamineRecord()
    }
}
